<?php

namespace App\Services;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsResponse;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use App\Models\PhoneMsgCode;
use Darabonba\OpenApi\Models\Config;
use Nette\Utils\Random;

class SmsService
{
    public static function createClient(){
        $config = new Config([
            "accessKeyId" => config('Sms.AccessKeyID'),
            "accessKeySecret" => config('Sms.AccessKeySecret'),
        ]);
        //访问的域名
        $config->endpoint = config('Sms.Endpoint');
        return new Dysmsapi($config);
    }

    /**
     * @param $phone stirng 手机号
     * @param $code stirng 验证码
     * @param $scene stirng 场景
     * @return bool
     */
    public function sendMessage($phone,$code='',$scene){
        $client = self::createClient();
        //判断这个手机号24小时内发送的次数
        $count = PhoneMsgCode::query()->where('phone',$phone)
            ->whereBetween('created_at',[date("Y-m-d H:i:s",time()-24*3600),date("Y-m-d H:i:s")])
            ->count();
        if ($count >=20 ){
            throw new \Exception('最近24小时发送短信已经达到20条',-1);
        }
        $count = PhoneMsgCode::query()->where('phone',$phone)
            ->whereBetween('created_at',[date("Y-m-d H:i:s",time()-3600),date("Y-m-d H:i:s")])
            ->count();
        if ($count >=5 ){
            throw new \Exception('最近一小时发送短信已经达到5条',-1);
        }
        //$code = Random::generate(6,'0-9');//验证码
        $sendSmsRequest = new SendSmsRequest([
            "signName" => config('Sms.SignName'),
            "templateCode" => $scene,
            "phoneNumbers" => $phone,
            "templateParam" => '{"code":"'.$code.'"}'
        ]);
        $runtime = new RuntimeOptions([]);
        $SendSmsResponse = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
        if ($SendSmsResponse->body->message !== 'OK') {
            throw new \Exception($SendSmsResponse->body->message,-1);
        }
        PhoneMsgCode::query()->insert([
            'phone'=>$phone,
            'code'=>$code,
            'created_at'=>now()
        ]);
        return true;
    }
}
